package com.zzl.myblog.View.Fragment;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;

import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.zzl.myblog.Bean.ResponseBean.UserCollectArticleBean;
import com.zzl.myblog.Bean.ViewBean.RvAboutBean;
import com.zzl.myblog.Bean.ViewBean.blog;
import com.zzl.myblog.R;
import com.zzl.myblog.Utils.GlideImageLoader;
import com.zzl.myblog.Utils.HttpUtil;
import com.zzl.myblog.Utils.LogUtil;
import com.zzl.myblog.Utils.SqliteUtils;
import com.zzl.myblog.Utils.responseUtility;
import com.zzl.myblog.View.Activity.WebActivity;
import com.zzl.myblog.View.Activity.editBlog;
import com.zzl.myblog.View.Activity.editUser;
import com.zzl.myblog.View.Adapter.AboutAdapter;
import com.zzl.myblog.View.NoScrollListView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


/**
 * 用户界面碎片
 */
public class UserFragment extends Fragment {
    static String username;
    String TAG = "UserFragment";
    View rootView;

    Banner banner;  // 控件--Banner
    ArrayList<String> images = new ArrayList<>(); // 数据源--照片URL集

    Map<String,String> map = new HashMap<>();
    List<RvAboutBean> rvAboutBeanList = new ArrayList<>();  // 数据源：博客项实例
    RecyclerView rvAbout;   // 控件--RecycleView
    AboutAdapter aboutAdapter;

    RelativeLayout clearStorage_rv;  // 控件--TextView 清除缓存
    RelativeLayout userInfo_rv; // 控件--TextView 用户信息管理

    static List<UserCollectArticleBean.ArticleListBean> CollectArticleBeanList = new ArrayList<>() ;  // 数据源：收藏文章实例
    static List<String> arrStr; // 数据源--提取文章标题
    NoScrollListView lvCollect; // 控件--NoScrollListView
    static ArrayAdapter<String> adapter;

    AlertDialog alertDialog;

    public UserFragment() {
        // Required empty public constructor
    }

    public static UserFragment newInstance(String username) {
        // 新建 UserFragment
        UserFragment fragment = new UserFragment();
        // Bundle 赋值
        Bundle bundle = new Bundle();
        bundle.putString("username", username);
        // 绑定 Bundle
        fragment.setArguments(bundle);
        // 返回 fragment
        return fragment;
    }

    //创建碎片视图
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_user, container, false);
        // 获得控件
        initView();
        assert getArguments() != null;//判空处理
        //拿到 Bundel 值
        username = getArguments().getString("username");//获取账号
        Log.d(TAG, "onCreateView: username " + username);
        return rootView;
    }

    //重新获取焦点时 重新加载数据（因为可能用户有新的收藏文章 需要重新从sqLite数据库中查询并显示）
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onResume() {
        super.onResume();
        // 重新请求收藏文章
        initData();
    }

    // 碎片是否可见，可见下才重新加载数据
    // https://blog.csdn.net/kristch_wu/article/details/80000148
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Log.d(TAG, "setUserVisibleHint: " + isVisibleToUser);
        
        if (isVisibleToUser) {   // 在最前端显示 相当于调用了onResume();
            //用户可见 获取数据并将数据放到视图控件中
            initData();
            fetchData();
        }
    }

    //实例化控件
    @RequiresApi(api = Build.VERSION_CODES.N)
    public void initView() {
        banner = rootView.findViewById(R.id.user_fragment_banner);
        rvAbout = rootView.findViewById(R.id.rv_user_fragment_about);
        lvCollect = rootView.findViewById(R.id.lv_collect_article);
        clearStorage_rv = rootView.findViewById(R.id.clearStorage_rvLayout);
        userInfo_rv = rootView.findViewById(R.id.user_info_rvLayout);
        // 点击事件--清除缓存
        clearStorage_rv.setOnClickListener(v -> {
            alertDialog = new AlertDialog.Builder(Objects.requireNonNull(UserFragment.this.getActivity()))
                    .setMessage("是否清除缓存？")
                    .setPositiveButton("确定",(dialogInterface, i13) -> {
                        // 清除sqlite中表数据
                        String msg = SqliteUtils.clearAll();
                        Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
                        initData();
                    })
                    .setNegativeButton("取消",(dialogInterface, i12) -> {
                        //只隐藏对话框即可
                        alertDialog.hide();
                    })
                    .create();
            alertDialog.show();
        });
        // 点击跳转--用户管理
        userInfo_rv.setOnClickListener(v ->{
            //根据URL创建web活动
            Intent intent = new Intent(getActivity(), editUser.class);
            intent.putExtra("username", username);
            startActivity(intent);
        });
    }

    /*
        完成 banner、博客地址的数据获取与填入
        完成 收藏文章的数据获取
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    protected void initData() throws NullPointerException {
        LogUtil.d(TAG, "initData");
        /*
        访问服务器，拿到收藏博客数据项
         */
        try {
            String params = "?username="+username;
            HttpUtil.collect_GET("collect", params, new Callback() {
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    assert response.body() != null;

                    String json = response.body().string();

                    Log.i("json",json);

                    CollectArticleBeanList =responseUtility.parse_UserCollectArticleBean(json).getArticleList();

                    fetchData();
                }
                @Override
                public void onFailure(Call call, IOException e) {

                }
            });
        }catch (Exception e){
            Log.i(TAG,e.getMessage());
        }

        // 关于博客地址 置空[因为每次都会重新加载，必须置空]
        rvAboutBeanList = new ArrayList<>();
        // 同理，images 置空
        images = new ArrayList<>();
        // images 置固定值
        images.add("https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=827960158,3435267204&fm=11&gp=0.jpg");
        images.add("https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2698156000,3689746818&fm=11&gp=0.jpg");
        images.add("https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1971287035,1923067534&fm=11&gp=0.jpg");
        images.add("https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=477692263,1318691853&fm=11&gp=0.jpg");
        images.add("https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3434335322,3604071306&fm=11&gp=0.jpg");
        images.add("https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2147475898,2163344652&fm=11&gp=0.jpg");

        /*
        banner轮播图-配置
         */
        banner.setImages(images).setImageLoader(new GlideImageLoader());
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        banner.setDelayTime(2500);
        banner.start();

        /*
        RecycleView-配置
         */
        rvAbout.setHasFixedSize(true);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvAbout.setLayoutManager(layoutManager);

        /*
        博客地址，从本地Sqlite查询，每次都先置空
         */
        map.clear();

        // 博客空map,置初值URL【本地服务器发404页面】
        map.put("myGithub","http://192.168.43.207:3000");
        map.put("myCSDN","http://192.168.43.207:3000");
        map.put("myGitee","http://192.168.43.207:3000");


        // 从本地Sqlite查询，并转入map
        List<blog> blogList = SqliteUtils.queryUser(username);
        if (blogList.size()!=0){    // 本地有用户博客记录
            blog blog = blogList.get(0);
            if(blog.getGiteeURL().contains("http")){    // 更改map初值，为用户之前存储过的URL
                map.replace("myGitee",blog.getGiteeURL());
            }
            if(blog.getCSDNURL().contains("http")){
                map.replace("myCSDN",blog.getCSDNURL());
            }
            if(blog.getGitHubURL().contains("http")){
                map.replace("myGithub",blog.getGitHubURL());
            }
        }else{
            Toast.makeText(getActivity(), username+",你还没有添加过博客地址！快添加几个试试！", Toast.LENGTH_SHORT).show();
        }

        // 初始化rv 的数据项
        RvAboutBean myGithub = new RvAboutBean(R.mipmap.github, "GitHub首页", map.get("myGithub"));
        RvAboutBean myCSDN = new RvAboutBean(R.mipmap.csdn, "CSDN博客首页", map.get("myCSDN"));
        RvAboutBean myGitee = new RvAboutBean(R.mipmap.mayun, "Gitee首页", map.get("myGitee"));
        rvAboutBeanList.add(myGithub);
        rvAboutBeanList.add(myCSDN);
        rvAboutBeanList.add(myGitee);

        //实例化MyAdapter并传入rv数据项
        aboutAdapter = new AboutAdapter(rvAboutBeanList, getContext());

        //自定义点击事件
        aboutAdapter.setOnClickListener(new AboutAdapter.OnAboutItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                //根据URL创建web活动
                Intent intent = new Intent(getActivity(), WebActivity.class);
                intent.putExtra("webURL", rvAboutBeanList.get(position).getAboutUrlStr());
                intent.putExtra("username", username);
                startActivity(intent);
            }

            @Override
            public void onItemLongClick(View view, int position) {
                //根据URL创建web活动
                Intent intent = new Intent(getActivity(), editBlog.class);
                intent.putExtra("username", username);
                startActivity(intent);
            }
        });

        //为RecyclerView对象mRecyclerView设置adapter
        rvAbout.setAdapter(aboutAdapter);

    }

    /*
        完成 收藏文章的数据填入
     */
    public void fetchData() {
            // 数据源置空
            arrStr = new ArrayList<>();
            // 提取出所有的文字标题
            for (UserCollectArticleBean.ArticleListBean item : CollectArticleBeanList) {
                String title = item.getCollectTitles();
                if (!TextUtils.isEmpty(title)) {
                    //若文字标题大于10的字符长度，则截取前十字符，后面内容用...代替
                    if (title.length() > 28) {
                        title = title.substring(0, 28).concat("...");
                    }
                }
                arrStr.add(title);
            }
            // 填充数据到 rv
            loadRvView();

    }

    public void loadRvView() {
        // 新建并配置ArrayAapeter
        adapter = new ArrayAdapter<String>(Objects.requireNonNull(getActivity()),
                android.R.layout.simple_list_item_1, arrStr);
        // LvCollect 绑定adapter
        lvCollect.setAdapter(adapter);
        
        // 解决ScrollView嵌套ListView只显示一条的问题
        setListViewHeightBasedOnChildren(lvCollect);

        //-----------------------------------

        // 收藏列表-点击事件【跳转WebActivity】
        lvCollect.setOnItemClickListener((adapterView, view, position, l) -> {
            //根据URL创建web活动
            Intent intent = new Intent(getActivity(), WebActivity.class);
            intent.putExtra("webURL", CollectArticleBeanList.get(position).getCollectUrl()); // ArticleBeanList.getPosition()
            startActivity(intent);
        });

        // 收藏列表-长按事件【取消收藏】
        // https://blog.csdn.net/u011500931/article/details/41938115
        lvCollect.setOnItemLongClickListener((adapterView, view, position, l) -> {
                    alertDialog = new AlertDialog.Builder(Objects.requireNonNull(UserFragment.this.getActivity()))
                    .setMessage("是否取消收藏该文章 ?")
                    .setPositiveButton("确定", (dialogInterface, i13) -> {
                            Log.i("collectUrl",CollectArticleBeanList.get(position).getCollectUrl());
                            String params = "?username="+username+"&collectUrl="+CollectArticleBeanList.get(position).getCollectUrl();
                            try {
                                //删除对应服务器数据源
                                HttpUtil.collect_DELETE("collect/delete",params, new Callback() {
                                    @Override
                                    public void onResponse(Call call, Response response) throws IOException {
                                        Looper.prepare();
                                        Toast.makeText(getActivity(), "删除成功！", Toast.LENGTH_SHORT).show();
                                        Looper.loop();
                                        Log.d(TAG, "onResponse: " + response.body().string());
                                    }
                                    @Override
                                    public void onFailure(Call call, IOException e) {
                                        Log.d(TAG, "onFailure: " +"请求失败");
                                    }
                                });
                            }catch (Exception e){
                                Log.i("deleteArticle","出错了"+e.getMessage());
                            }
                        // 该表title数组
                        arrStr.remove(position);//删除数据源,移除集合中当前下标的数据

                        // 刷新apater
                        adapter.notifyDataSetChanged();//刷新被删除的地方

                    })
                    .setNegativeButton("取消", (dialogInterface, i12) -> {
                        //只隐藏对话框即可
                        alertDialog.hide();
                    })
                    .create();
            alertDialog.show();
            return true;//表示此事件已经消费，不会触发单击事件
        });
    }

    /**
     * 解决ScrollView嵌套ListView只显示一条的问题
     *
     * @param listView
     */
    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() *
                (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
        listView.invalidate();
    }

}
